package ntd.util.modular.data.util;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.LFUCache;
import cn.hutool.core.lang.Opt;
import cn.hutool.log.StaticLog;
import ntd.util.modular.data.entity.DataAcquisitionRule;
import ntd.util.modular.data.util.handle.ComDataGetRule;

public class UtilDataAcquisitionManager {

    private static final LFUCache<String, ComDataGetRule> COM_DATA_GET_RULES = CacheUtil.newLFUCache(20);

    public static void updateRule(DataAcquisitionRule dataAcquisitionRule) {
        removeRule(dataAcquisitionRule.getId());
        handleRule(dataAcquisitionRule);
    }

    public static void removeRule(String id) {
        Opt.ofNullable(COM_DATA_GET_RULES.get(id)).ifPresent(comDataGetRule -> {
            comDataGetRule.close();
            COM_DATA_GET_RULES.remove(id);
        });
    }

    public static void handleRule(DataAcquisitionRule dataAcquisitionRule) {
        ComDataGetRule comDataGetRule = COM_DATA_GET_RULES.get(dataAcquisitionRule.getId(), () ->
                FactoryHandleRule.get(dataAcquisitionRule.getEnumProtocolType()));
        Object res = comDataGetRule.handle(dataAcquisitionRule);
        StaticLog.info("规则[{}]执行完成", dataAcquisitionRule.getName());
    }

}
